//
//  SHMainViewController.swift
//  ServiceHelper
//
//  Created by Xuedan on 15/12/12.
//  Copyright © 2015年 Stan Wu. All rights reserved.
//

import UIKit

class SHMainViewController: UIViewController ,UIActionSheetDelegate,UITabBarControllerDelegate{
    
    var tabBarBgImg : UIImageView?
    var tabBarBgImgSelected:UIImageView?
    var tabbar_zsj : UITabBarController!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //隐藏自带的tabBarItem
//        self.tabBar.hidden = true
        //自定义视图
//        customTabBar()
        //加载视图
        loadViewController()
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(SHMainViewController.hideTabBar), name: "HiddenTabBar", object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(SHMainViewController.showTabBar), name: "ShowTabBar", object: nil)
        // Do any additional setup after loading the view.
    }
    
    func hideTabBar(){
//        tabBarBgImg?.hidden = true
    }
    
    func showTabBar(){
//        tabBarBgImg?.hidden = false
    }
    
    func test(tap:UITapGestureRecognizer){
        let view=tap.view
        let index=view!.tag as Int
        let z=(index)*172+330
        let c=CGFloat(z)
//        var x:CGFloat=5.0 + c
        let x:CGFloat =  c
        let y=tabBarBgImg!.frame.size.height/2-45/2
//        UIView.beginAnimations("test",context:nil)
        tabBarBgImgSelected!.frame = CGRectMake(x ,y+5, 22, 22)
       
        let imgvSelectedIndex1 = tabBarBgImg?.viewWithTag(1000) as! UIImageView
        let imgvSelectedIndex2 = tabBarBgImg?.viewWithTag(1001) as! UIImageView
        let imgvSelectedIndex3 = tabBarBgImg?.viewWithTag(1002) as! UIImageView
        
        let lblSelectedIndex1 = tabBarBgImg?.viewWithTag(2000) as! UILabel
        let lblSelectedIndex2 = tabBarBgImg?.viewWithTag(2001) as! UILabel
        let lblSelectedIndex3 = tabBarBgImg?.viewWithTag(2002) as! UILabel
        
        var images=["gary_all_orders.png","gary_waiting.png","gary_set_up.png"]
        var colors = [UIColor(red: 0.28, green: 0.56, blue: 0.88, alpha: 1),UIColor.grayColor(),UIColor.grayColor()]

        if index == 1000{
            images = ["bule_all_orders.png","gary_waiting.png","gary_set_up.png"]
            colors = [UIColor(red: 0.28, green: 0.56, blue: 0.88, alpha: 1),UIColor.grayColor(),UIColor.grayColor()]
           
        }else if index == 1001{
            images = ["gary_all_orders.png","bule_waiting.png","gary_set_up.png"]
            colors = [UIColor.grayColor(),UIColor(red: 0.28, green: 0.56, blue: 0.88, alpha: 1),UIColor.grayColor()]
        }else{
            images = ["gary_all_orders.png","gary_waiting.png","bule_set_up.png"]
            colors = [UIColor.grayColor(),UIColor.grayColor(),UIColor(red: 0.28, green: 0.56, blue: 0.88, alpha: 1)]
        }
        imgvSelectedIndex1.image = UIImage(named: images[0])
        imgvSelectedIndex2.image = UIImage(named: images[1])
        imgvSelectedIndex3.image = UIImage(named: images[2])
        
        lblSelectedIndex1.textColor = colors[0]
        lblSelectedIndex2.textColor = colors[1]
        lblSelectedIndex3.textColor = colors[2]
        
        
//        tabBarBgImgSelected?.backgroundColor = UIColor.blueColor()
//        UIView.commitAnimations()
        
        //跳转页面
//        self.selectedIndex=view!.tag-1000
        
        if view?.tag == 1002{
            
                let actionSheet = UIActionSheet()
                actionSheet.title = "选择要进行的操作"
                actionSheet.delegate = self
                actionSheet.addButtonWithTitle("注销")
                actionSheet.addButtonWithTitle("取消")
                actionSheet.tag = 100
               actionSheet.showInView(self.view)

        }
    }
    
    func customTabBar(){
        
        let height=UIScreen.mainScreen().bounds.size.height
        let width=UIScreen.mainScreen().bounds.size.width
        let tabW=width
        let tabH=height-49
        tabBarBgImg=UIImageView(frame:CGRectMake(0,tabH,tabW,49))
        
        //打开事件
        tabBarBgImg!.userInteractionEnabled=true
//        tabBarBgImg!.image=UIImage(named:"tab_bg_all")
        tabBarBgImg?.backgroundColor = UIColor(red: 0.93, green: 0.93, blue: 0.93, alpha: 1)
        
        //选中背影图片
        let y=tabBarBgImg!.frame.size.height/2-45/2
        tabBarBgImgSelected = UIImageView(frame:CGRectMake(330,y+5, 22, 22))
        tabBarBgImgSelected!.image=UIImage(named:"bule_all_orders.png")
//        tabBarBgImgSelected?.backgroundColor = UIColor.blueColor()
        tabBarBgImg!.addSubview(tabBarBgImgSelected!)
        
        var x:CGFloat=0
        var images=["bule_all_orders.png","gary_waiting.png","gary_set_up.png"]
        var colors = [UIColor(red: 0.28, green: 0.56, blue: 0.88, alpha: 1),UIColor.grayColor(),UIColor.grayColor()]
        var titles=["全部订单","等待确认","系统设置"]
        let titleFont=UIFont.systemFontOfSize(10)
        for  index in 0 ..< 3 {
            let imgView=UIImageView(frame:CGRectMake( x+330, y+5, 22, 22))
            //添加事件
            imgView.userInteractionEnabled=true
            imgView.tag=index+1000
            let tap=UITapGestureRecognizer(target:self,action:#selector(SHMainViewController.test(_:)))
            imgView.addGestureRecognizer(tap)
            
            imgView.image = UIImage(named:images[index])
            tabBarBgImg!.addSubview(imgView)
            let title=UILabel(frame:CGRectMake(x+320,y+26,60,15))
            title.text=titles[index]
            title.font=titleFont
            title.textColor = colors[index]
            title.tag = 2000+index
            tabBarBgImg!.addSubview(title)
            x+=172
        }
        self.view.addSubview(tabBarBgImg!)
        
    }
    
    
    func loadViewController(){
//        let vcAllOrders = HMAllOrdersViewController()
//        let allItem = UITabBarItem(tabBarSystemItem: .Favorites, tag: 1)
//        vcAllOrders.tabBarItem = allItem
//        vcAllOrders.strNavTitle = "全部订单"
//        let navAllOrders = UINavigationController(rootViewController: vcAllOrders)
       
        
        let vcOrdersList = SHOrdersListViewController()
        let navOrdersList = UINavigationController(rootViewController: vcOrdersList)
        navOrdersList.title = "全部订单"
        navOrdersList.tabBarItem.image=UIImage(named: "gary_all_orders.png")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal); //默认显示图片
        navOrdersList.tabBarItem.selectedImage=UIImage(named: "bule_all_orders.png")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal); //选中后的图片

//        let allItem = UITabBarItem(tabBarSystemItem: .Favorites, tag: 1)
//        vcOrdersList.tabBarItem = allItem
//        vcOrdersList.strNavTitle = "全部订单"
        
        
        let vcWaitingOrders = SHOrdersListViewController()
        let navWaitingOrders = UINavigationController(rootViewController: vcWaitingOrders)
        navWaitingOrders.title = "等待确认"
        navWaitingOrders.tabBarItem.image=UIImage(named: "gary_waiting.png")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal); //默认显示图片
        navWaitingOrders.tabBarItem.selectedImage=UIImage(named:
            "bule_waiting.png")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal);
//        navWaitingOrders.tabBarItem.tag = 1
        //选中后的图片
//        vcWaitingOrders.isFromWaitingOrder = true
//        vcWaitingOrders.strNavTitle = "等待确认"
//        let waitingItem = UITabBarItem(tabBarSystemItem: .Favorites, tag: 1)
//        vcWaitingOrders.tabBarItem = waitingItem
        let vcMore  = SHSettingViewController()
        let navMore = UINavigationController(rootViewController: vcMore)
        navMore.title = "系统设置"
        navMore.tabBarItem.image=UIImage(named: "gary_set_up.png")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal); //默认显示图片
        navMore.tabBarItem.selectedImage=UIImage(named:
            "bule_set_up.png")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal);
        navMore.tabBarItem.tag = 2
        
        tabbar_zsj = UITabBarController()
        tabbar_zsj.delegate = self
        let controls = [navOrdersList,navWaitingOrders,navMore]
//        tabbar_zsj.setViewControllers(controls, animated: true)
        //.自定义工具栏
        tabbar_zsj.tabBar.backgroundColor=UIColor.clearColor()
        //底部工具栏背景颜色
        tabbar_zsj.tabBar.barTintColor=UIColor(red: 0.93, green: 0.93, blue: 0.93, alpha: 1)
        //.设置底部工具栏文字颜色（默认状态和选中状态）
        UITabBarItem.appearance().setTitleTextAttributes(NSDictionary(object:UIColor.grayColor(), forKey:NSForegroundColorAttributeName) as? [String : AnyObject], forState:UIControlState.Normal);
        UITabBarItem.appearance().setTitleTextAttributes(NSDictionary(object:UIColor(red: 0.28, green: 0.56, blue: 0.88, alpha: 1), forKey:NSForegroundColorAttributeName) as? [String : AnyObject], forState:UIControlState.Selected)
        
        //设置开始选中那个控制器
        tabbar_zsj.selectedIndex = 1
        /**********************************************************/
        // 微标签 的设置
       
        /**********************************************************/
        
        // 将三个标签，添加到标签栏控制器
        tabbar_zsj.viewControllers = controls
        /**********************************************************/
        //这个方法，必须在，所有的标签都设置到tabbar 上才可以设置，否则报错
//        tabbar_zsj.selectedViewController = vcOrdersList
        /*
        错误是：eason: '-[UITabBarController setSelectedViewController:] only a view controller in the tab bar controller's list of view controllers can be selected.
        */
        //添加到widows 上面进行显示
        //\\
//        let myDelegate:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
       tabbar_zsj.delegate = self
       
//       myDelegate.window?.rootViewController = tabbar_zsj
        UIApplication.sharedApplication().delegate?.window!!.rootViewController = tabbar_zsj
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    // MARK: - UIActionSheet Delegate
    func actionSheet(actionSheet: UIActionSheet, didDismissWithButtonIndex buttonIndex: Int) {
        if actionSheet.tag == 100 {
            if buttonIndex >= 0 {
                let buttonTitle = actionSheet.buttonTitleAtIndex(buttonIndex)
                if buttonTitle=="注销"{
                    NSNotificationCenter.defaultCenter().postNotificationName("LogoutAccount", object: nil)
                }
                
            }
        }
    }
    
    func tabBarController(tabBarController: UITabBarController, shouldSelectViewController viewController: UIViewController) -> Bool {
        let navVc = viewController as! UINavigationController
        if navVc.viewControllers[0].isKindOfClass(SHSettingViewController.classForCoder()){
            return false
        }else{
            return true
        }
    }
    
    
//    override func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {
//        if item.tag == 2{
////            let actionSheet = UIActionSheet()
////            actionSheet.title = "选择要进行的操作"
////            actionSheet.delegate = self
////            actionSheet.addButtonWithTitle("注销")
////            actionSheet.addButtonWithTitle("取消")
////            //        var actionSheet = UIActionSheet(title: "选择要进行的操作", delegate: self, cancelButtonTitle: "取消", destructiveButtonTitle: nil, otherButtonTitles:nil)
////            //        actionSheet.addButtonWithTitle("注销")
////            //                actionSheet.showFromRect(view!.frame, inView: self.view, animated: true)
////            //            actionSheet.showFromRect(lblSelectedIndex3.frame, inView: self.view, animated: true)
////            actionSheet.tag = 100
////            actionSheet.showInView(self.view)
//            
//        }
//    }

    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
